<template>
  <a-table
    :pagination="pagination"
    @change="tableChange"
    size="small"
    :columns="props.columns"
    :data-source="data"
  >
    <template #bodyCell="{ column, record, index, text }">
      <slot name="bodyCell" :column="column" :record="record" :index="index" :text="text"></slot>
    </template>
  </a-table>
</template>
<script lang="ts" setup>
import { defineProps, ref } from 'vue'
defineOptions({
  name: 'DataTable',
})
const props = defineProps({
  columns: {
    type: Array,
    default: () => [],
  },
  getApi: {
    type: Function,
    default: () => {
      return Promise.resolve([])
    },
  },
  defaultData: {
    type: Array,
    default: () => [],
  },
  formState: {
    type: Object,
    default: () => {},
  },
})
const pagination = ref({
  total: 0,
  pageSize: 10,
  current: 1,
})
const getList = (goCurrent: boolean = false) => {
  if(goCurrent) pagination.value.current = 1;
  const params = {
    ...props.formState,
    pageNo: pagination.value.current,
    pageSize: pagination.value.pageSize,
  }
  props.getApi(params).then((res: { records: Record<string, string>[], total: number }) => {
    data.value = res.records
    pagination.value.total = res.total
  })
}
const data = ref(props.defaultData)
getList()
const tableChange = (pag: { current: number; pageSize: number }) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  getList()
}
defineExpose({
  getList,
})
</script>
